-module(ham_user).
-author("hpj").

-import(proplists, [get_value/2, get_value/3]).

-include_lib("emysql/include/emysql.hrl").

-include("mysql.hrl").

-include("emqttd.hrl").

-include("emqttd_topic.hrl").

-include("emqttd_packet.hrl").

%% API
-export([handle/1]).

%% register user
handle(Params) ->
  ActionType = get_value(<<"action_type">>,Params),
  handle(ActionType,Params).

handle(1,Params) ->
  UID_LIST = get_value(<<"uid_list">>,Params),
  UID_STATE_LIST = 
    lists:foldl(fun(UID,Acc) ->
      [Record] = mnesia:dirty_read(user_info,UID),
      [[{<<"uid">>,UID},{<<"state">>,Record#user_info.status}]] ++ Acc
      end,[],UID_LIST),
  {ok, [{<<"code">>,0},{<<"uid_state_list">>,UID_STATE_LIST}]};

%% url server sub user offline online state
handle(2, Data) ->
    Uidlist = get_value(<<"uid_list">>,Data),
    Uid = get_value(<<"send_uid">>,Data),
    Type = get_value(<<"type">>,Data),
    {ok,Im} = application:get_env(ham_server,emqttd),
    rpc:cast(Im, emqttd_ham, to_sub_state, [Uid, Uidlist, Type]),
     {ok, [{<<"code">>,0}]};

handle(_Method, Req) ->
  Response = jsx:encode([{<<"ret">>,4},{<<"message">>,<<"api invalid">>}]),
  Req:ok({"text/plan",Response}).